﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.IoC;
using Kooboo.Domain;

namespace Kooboo.Commerce.Contexts.Taxes
{
    public static class EditorBehavior
    {
        public static void Post(this IEditor actor, ITax tax)
        {
            using (var transaction = ObjectContainer.CreateInstance<TransactionContext>())
            {
                try
                {
                    var repository = ContextContainer.Current.Resolve<ITaxRepository>();
                    repository.Post(tax);
                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }

        }

        public static void Put(this IEditor actor, ITax tax)
        {
            using (var transaction = ObjectContainer.CreateInstance<TransactionContext>())
            {
                try
                {
                    var repository = ContextContainer.Current.Resolve<ITaxRepository>();
                    repository.Put(tax);

                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }

        public static void Delete(this IEditor actor, ITax tax)
        {
            using (var transaction = ObjectContainer.CreateInstance<TransactionContext>())
            {
                try
                {
                    var productRepository = ContextContainer.Current.Resolve<IProductRepository>();

                    productRepository.Products
                        .Where(i => i.Tax.Id == tax.Id)
                        .ToUpdate()
                        .Set(i => i.Tax, null)
                        .Execute();

                    var taxRepository = ContextContainer.Current.Resolve<ITaxRepository>();
                    taxRepository.Delete(tax);

                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }

        }
    }
}
